/**
 * 
 */
package org.wsocket.thread;

import java.util.Collection;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.log4j.Logger;
import org.wsocket.WSocket;
import org.wsocket.Exception.WSocketException;
import org.wsocket.config.WSocketLoader;

/**
 * @author Jeffyd, JoJo
 */

public class ThreadPool {
	private static Logger log=Logger.getLogger(ThreadPool.class);
	private static ExecutorService threadPool_IO = null;
	private static ExecutorService threadPool_generate = null;
	
	private ThreadPool(){}

	/**
	 * init threadPool
	 */
	static {
		threadPool_IO = Executors.newFixedThreadPool(WSocket.getThreadPoolSize());
		threadPool_generate = Executors.newFixedThreadPool(WSocket.getPortSizes()+1);
	}

	/**
	 * add a task to threadPool
	 * @param task
	 * @throws WSocketException 
	 */
	public static void assginTask(ThreadTask task) throws WSocketException {
		try {
			threadPool_IO.execute(task);
		} catch (Exception e) {
			log.error(e);
			throw new WSocketException(e);
		}
	}
	
	/**
	 * add many tasks to threadPool. 
	 * invokeAll will return while all tasks finished.
	 * @param Callable<T>
	 * 
	 */
	public static void assginTasks(Collection<Callable<Boolean>> tasks)
			throws WSocketException {
		try {
			threadPool_IO.invokeAll(tasks);
		} catch (Exception e) {
			log.error(e);
			throw new WSocketException(e);
		}
	}
	
	/**
	 * add many tasks to threadPool. 
	 * invokeAll will return while all tasks finished.
	 * @param Callable<T>
	 * 
	 */
	public static void assginGenerateTask(ThreadTask task) throws WSocketException {
		try {
			threadPool_generate.execute(task);
		} catch (Exception e) {
			log.error(e);
			throw new WSocketException(e);
		}
	}

}
